<template>
  <view class="page">
    <view v-if="$data.info">
      <!-- 地址 -->
      <view class="address" @tap="onCheckAddress">
        <view class="address_left">
          {{ $data.address || "请选择服务地址" }}
        </view>
        <view class="address_right">
          <image :src="ImgIconRightGray" />
        </view>
      </view>
      <!-- 产品详情 -->
      <view class="detail">
        <view class="detail_img">
          <image :src="$data.info.DomesticService._picurl" />
        </view>
        <view class="detail_content">
          <view class="detail_content--title">
            {{ $data.info.DomesticService.title }}
          </view>
          <view class="detail_content--desc">
            已选：
            {{ $data.chooseSkuName }}
          </view>
          <view class="detail_content--price text-price">
            {{ $data.info.DomesticService.totalPrice }}
          </view>
        </view>
      </view>
      <!-- 服务时间 -->
      <view class="time">
        <view class="time_title">服务时间</view>
        <view class="time_content" @tap="() => ($data.chooseTimeShow = true)">
          <view class="time_content--check">
            <text v-if="$data.time" class="text-main-color">
              {{ $data.time }}
            </text>
            <text v-else class="text-gray">请添加服务时间</text>
          </view>
          <view class="time_content--icon">
            <image :src="ImgIconRightGray" />
          </view>
        </view>
      </view>
      <!-- 优惠券 -->
      <!-- <view class="coupon">
        <view class="coupon_title">优惠券</view>
        <view class="coupon_content" @tap="onCheckCoupon">
          <view class="coupon_content--check">
            <text v-if="$data.couponName" class="text-main-color">
              {{ $data.couponName }}
            </text>
            <text v-else class="text-gray">
              <text v-if="$data.couponCanUseCount > 0">
                有{{ $data.couponCanUseCount }}张优惠券可使用
              </text>
              <text v-else>暂无可用优惠券</text>
            </text>
          </view>
          <view class="coupon_content--icon">
            <image :src="ImgIconRightGray" />
          </view>
        </view>
      </view> -->
      <!-- 备注 -->
      <view class="card margin-top">
        <view class="card_title margin-bottom">备注</view>
        <up-textarea
          v-model="$data.remark"
          placeholder="如有其他要求请备注"
          :height="100"
          :maxlength="150"
          border="surround"
          count
        ></up-textarea>
      </view>
      <!-- 温馨提示 -->
      <view class="card margin-top">
        <up-parse :content="$data.tips"></up-parse>
      </view>
      <!-- 底部结算按钮 -->
      <view class="foot foot_box">
        <view class="bill text-nowarp" @tap="() => ($data.billShow = true)">
          <text>需支付</text>
          <text class="text-main-color text-price margin-lr-sm text-xl">
            {{ $data.info.DomesticService.totalPrice }}
          </text>
          <u-icon :name="$data.billShow ? 'arrow-up' : 'arrow-down'"></u-icon>
        </view>
        <view class="btn btn_save" @tap="onSave">去结算</view>
      </view>
    </view>
    <PopupChooseTime
      v-model:show="$data.chooseTimeShow"
      @confirm="onChooseTime"
    />
    <PopupBill
      v-model:show="$data.billShow"
      :info="$data.info"
      :currentCoupon="$data.currentCoupon"
    />
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick } from "vue";
import { onLoad, onShow, onReady, onUnload } from "@dcloudio/uni-app";
import BasicConfig from "@/utils/config";
import { eventBus } from "../../../enums/eventBus";
import { skuInputType } from "../../../enums/sku";
import { useGetLocationStorage } from "../../../hooks/useStorage";
import {
  freePay,
  orderConfirm,
  orderImmediate,
} from "../../../api/Interface/order";
import errorCode from "../../../utils/http/errorCode";
import { ImgIconRightGray } from "../../../utils/iconMap";
import { jumpPage } from "../../../utils/route/route";
import PopupChooseTime from "./components/PopupChooseTime.vue";
import { couponTypeConfig, couponUseTypeConfig } from "../../../enums/coupon";
import PopupBill from "./components/PopupBill.vue";
import {
  orderSourceType,
  orderStatus,
  orderType,
  payType,
} from "../../../enums/order";
import { useLakalaPay, usePayment, useWechatPay } from "../../../hooks/usePay";
import { useImgSrc } from "../../../hooks/useImg";
import { useSubscribeTemplate } from "../../../hooks/useSubscribe";
import { subscribeEnum } from "../../../enums/subscribe";
import { useGetConfig } from "../../../hooks/useCommon";
import { configKeyEnum } from "../../../enums/common";

const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  chooseSkuList: [], // 选择的sku
  address: "", // 选择的地址
  couponName: "", // 选择的优惠券名称
  info: null,
  detail: {},
  chooseSkuName: "", // 已选sku名称
  isCanBuy: false, // 是否可以购买
  canBuyMessage: "", // 不可购买时的文案
  time: "", // 选择的服务时间
  timeStamp: 0, // 选择的服务时间时间戳
  coupon: "", // 选择的优惠券
  chooseTimeShow: false, // 选择日期
  couponCanUseCount: null, // 可用优惠券数量
  billShow: false, // 结算明细
  remark: "", // 备注
  tips: "", // 温馨提示
  currentCoupon: null, // 当前选择的优惠券信息
});
const params = reactive({
  cityCode: "", // 所在城市编码
  domesticServiceId: "", // 服务技能id
  domesticServiceSkuId: "", // 服务技能规格ID【domesticServiceSkuId和skuJson至少传一个】 选择的sku为单选时传这个
  userAddressId: "", // 地址ID
  userCouponId: "", // 选择的优惠券ID
  skuJson: "", // 多选规格"[{\"domesticServiceSkuId\":1,\"skuValue\":22},{\"domesticServiceSkuId\":2,\"skuValue\":33}]"
  firstStartServicedAt: 0, // 服务时间【十位时间戳】
});
const init = async () => {
  // 产品详情->确认订单通信
  uni.$on(eventBus.service.confirm, async (e = []) => {
    $data.chooseSkuList = e;
    console.log("$data.chooseSkuList", $data.chooseSkuList);
    // const len = $data.chooseSkuList.length;
    // 有输入的 需要传json
    const hasInput =
      $data.chooseSkuList.filter((c) => c.inputType == skuInputType.input)
        .length > 0;
    // 单选的
    if (!hasInput) {
      const sku = $data.chooseSkuList[0];
      const { domesticServiceSkuId } = sku;
      params.domesticServiceSkuId = domesticServiceSkuId;
    }
    // 多选的
    else if (hasInput) {
      const list = $data.chooseSkuList.map((m) => {
        const { _value, domesticServiceSkuId } = m;
        return {
          domesticServiceSkuId,
          skuValue: _value,
        };
      });
      params.skuJson = JSON.stringify(list);
    }
    await getData();
  });
  // 选择地址通信
  uni.$on(eventBus.service.address, async (e) => {
    $data.address = e.address;
    params.userAddressId = e.userAddressId;
    console.log("选择地址通信", e);
    await getData();
  });
  // console.log("confirm 页 init");
  // await getData();
};
const getData = async () => {
  const location = useGetLocationStorage();
  params.cityCode = location ? location.code : "";
  params.firstStartServicedAt = $data.timeStamp;
  console.log("请求 params", params);
  const { code, msg, data } = await orderConfirm(params);
  console.log("请求 getData 回调", code, msg, data);
  if (code === errorCode.success) {
    console.log("确认订单getData请求回调");
    $data.info = data;
    const { picArr, picurl } = $data.info.DomesticService;
    $data.info.DomesticService.picArr = picArr.map((m) => (m = useImgSrc(m)));
    $data.info.DomesticService._picurl = useImgSrc(picurl);
    $data.address = data.userAddress?.address;
    params.userAddressId = data.userAddress?.userAddressId;
    params.userCouponId = data.checkedCoupon?.userCouponId ?? "";
    $data.couponName = data.checkedCoupon?.title;
    $data.currentCoupon = data.checkedCoupon;
    if ($data.info.DomesticService.sku.length > 0) {
      $data.chooseSkuName = $data.info.DomesticService.sku
        .map((m) => m.skuTitle)
        .join(",");
    } else {
      $data.chooseSkuName = $data.chooseSkuList
        .map((m) => m.skuTitle)
        .join(",");
    }
    $data.isCanBuy = !!$data.info.DomesticService.isCanBuy;
    $data.canBuyMessage = $data.info.DomesticService.canBuyMessage;
    const availableCoupons = $data.info.couponArr?.availableCoupons ?? [];
    $data.couponCanUseCount = availableCoupons.length;
    console.log("$data.isCanBuy~", $data.isCanBuy);
    if (!$data.isCanBuy) {
      console.log("将要弹出showModal");
      uni.showModal({
        content: $data.canBuyMessage,
        showCancel: false,
        confirmText: "知道了",
        confirmColor: BasicConfig.MainColor,
      });
    }
  }
  useGetConfig({ key: configKeyEnum["日常确认订单温馨提示"] }).then((res) => {
    $data.tips = res;
  });
};
const onCheckAddress = () => {
  jumpPage({
    to: "/package-my/pages/addressManage/index",
    query: {
      fromType: eventBus.service.address,
    },
  });
};
const onChooseTime = (e) => {
  if (!e) return;
  const { time, label } = e;
  $data.timeStamp = time;
  $data.time = label;
  getData();
};
const onCheckCoupon = () => {
  const couponArr = $data.info.couponArr;
  if (couponArr && couponArr.availableCoupons) {
    couponArr.availableCoupons.forEach((item) => {
      item._open = false;
      item._couponTypeName = couponTypeConfig[item.couponType]?.typeName ?? "";
      item._useDate = couponUseTypeConfig[item.useType]?.desc ?? "";
      item._check = item.userCouponId == params.userCouponId;
    });
  }
  setTimeout(() => {
    uni.$emit(eventBus.service.useCoupon, couponArr, checkCouponCallback);
  }, 1000);
  jumpPage({
    to: "/package-my/pages/coupons/useCoupons",
  });
};
const checkCouponCallback = async (list) => {
  console.log("选择回调", list);
  await getData();
  if (list.length > 0) {
    params.userCouponId = list[0].userCouponId;
    $data.couponName = list[0].title;
    $data.currentCoupon = list[0];
  } else {
    params.userCouponId = "";
    $data.couponName = "";
    $data.currentCoupon = null;
  }
};
/** 结算 */
const onSave = () => {
  console.log("$data.timeStamp", $data.timeStamp);
  if (!$data.timeStamp) {
    BasicConfig.toast("您尚未添加服务时间，请添加服务时间后提交订单");
    return;
  }
  if (!params.userAddressId) {
    BasicConfig.toast("您尚未选择服务地址，请选择服务地址后提交订单");
    return;
  }
  const can = uni.canIUse("createOrder");
  console.log("can", can, tt, uni.createOrder);
  if (!can) {
    BasicConfig.toast("当前版本不支持创建订单，请升级到最新版本");
    return;
  }
  BasicConfig.loadToast("创建订单...");
  const sku = $data.chooseSkuList[0];
  let quantity = 1; // 数量
  if (sku.inputType == skuInputType.radio) {
    quantity = 1;
  }
  if (sku.inputType == skuInputType.input) {
    quantity = sku._value;
  }
  const goods = $data.info.DomesticService;
  // 透传字段
  const optinos = {
    userAddressId: params.userAddressId,
    domesticServiceId: goods.domesticServiceId,
    domesticServiceSkuId: sku.domesticServiceSkuId,
    firstStartServicedAt: $data.timeStamp, // params.firstStartServicedAt,
    hasRecorder: 1, // 是否允许开启工作记录仪 0.否 1.是
    life_trade_flag: 1, // 0：非融合链路（默认值）  1：走融合链路（标准融合/完全融合）
    dyProductId: sku.dyProductId,
		dyVersion: 1,
		cityCode: "", // TODO
  };
  // sku.domesticServiceSkuId = "7477763636107216931";
  const skuList = [
    {
      skuId: sku.dyProductId + "", // sku 商品Id 必传 string
      skuType: sku.inputType, // sku 商品类型 必传
      quantity, // 数量 必传
      price: Number(sku.dyPrice) * 100, // 价格 非商品库 sku 商品必传 number
      goodsInfo: {
        goodsName: goods.title, // 商品名称 必填
        goodsPhoto: goods._picurl, // 商品图片链接 必填
        goodsId: sku.dyProductId + "", // goods.domesticServiceId + "", // 商品ID 必填 string
        goodsType: orderType.service, // 商品类型 必填
        goodsLabels: goods.serviceTagNameArr, // 商品标签 非必填
        dateRule: "", // 使用规则 非必填
      },
      // extraInfo: {
      //   ticketName: "child", // 票种，非商品库门票类 sku 必传
      //   date: "2022-07-26", // 日期，非商品库门票类 sku 必传
      // },
    },
  ];
  const dyParams = {
    skuList,
    payment: {
      totalAmount: Number(sku.dyPrice) * 100, // goods.totalPrice, // 订单总价 必填
      totalDiscountAmount: 0, // 订单总折扣
    },
    callbackData: optinos, // 透传数据，开发者自定义字段 非必传
    tradeOption: optinos, // 透传数据，开发者自定义字段 非必传
    // callbackUrl: "https://test.qmgdj.com/api/pay/douYinPreOrderNotify", // 开发者自定义的预下单回调 URL(仅账号融合支持，完全融合不生效)
  };
  console.log("预下单params", dyParams);
  console.log("是否登录");
  // tt.login({
  //   success: (success) => {
  uni.createOrder({
    /** 单选 */
    // bindSku: ""
    // cover: ""
    // domesticServiceId: 30
    // domesticServiceSkuId: 76
    // inputType: 1
    // marketPrice: "160.00"
    // price: "150.00"
    // serviceTime: 50
    // skuIntro: "规格2的说明哦哦哦"
    // skuTitle: "规格2"
    // skuUnit: "次"
    // _backupValue: ""
    // _picurl: ""
    // _value: ""
    /** 输入 */
    // bindSku: ""
    // cover: "/storage/manage/20241207/e3fef0b30d9af0a42fe6c952289d0b4a.png"
    // domesticServiceId: 30
    // domesticServiceSkuId: 77
    // inputType: 2
    // marketPrice: "60.00"
    // price: "1.00"
    // serviceTime: 20
    // skuIntro: "规格3的说明哦哦哦"
    // skuTitle: "擦玻璃"
    // skuUnit: "个"
    // _backupValue: ""
    // _picurl: "https://qingmangguodaojia-test.oss-cn-hangzhou.aliyuncs.com/storage/manage/20241207/e3fef0b30d9af0a42fe6c952289d0b4a.png"
    // _value: "80"
    ...dyParams,
    success: (res) => {
      console.log("预订单下单成功", res);
      uni.hideLoading();
      jumpPage({
        to: "/package-service/pages/order/result",
        mode: "reLaunch",
      });
    },
    fail: (err) => {
      uni.hideLoading();
      console.log("预订单下单失败err", err);
      // createOrder:fail payment is cancelled
      if (err.errMsg.includes("payment is cancelled")) {
        jumpPage({
          to: `/package-service/pages/order/order?status=${orderStatus.awaitPay}`,
          mode: "reLaunch",
        });
      } else {
        uni.showModal({
          content: "下单失败，请稍后重试！",
          showCancel: false,
          confirmText: "知道了",
        });
      }
    },
  });
  //   },
  // });

  return;
  console.log("$data.timeStamp", $data.timeStamp);
  if (!$data.timeStamp) {
    BasicConfig.toast("您尚未添加服务时间，请添加服务时间后提交订单");
    return;
  }
  if (!params.userAddressId) {
    BasicConfig.toast("您尚未选择服务地址，请选择服务地址后提交订单");
    return;
  }
  console.log("onSave params", {
    domesticServiceId: params.domesticServiceId,
    domesticServiceSkuId: params.domesticServiceSkuId,
    userAddressId: params.userAddressId,
    userCouponId: params.userCouponId,
    payMode: payType.wechat,
    firstStartServicedAt: $data.timeStamp,
    skuJson: params.skuJson,
    hasRecorder: 1, // 是否允许开启工作记录仪 0.否 1.是
    remark: $data.remark,
  });
  uni.showModal({
    content: "确认结算?",
    confirmColor: BasicConfig.MainColor,
    success: async (success) => {
      if (success.confirm) {
        const query = {
          domesticServiceId: params.domesticServiceId,
          domesticServiceSkuId: params.domesticServiceSkuId,
          userAddressId: params.userAddressId,
          userCouponId: params.userCouponId,
          payMode: payType.wechat,
          firstStartServicedAt: $data.timeStamp,
          skuJson: params.skuJson,
          hasRecorder: 1, // 是否允许开启工作记录仪 0.否 1.是
          remark: $data.remark,
        };
        const { code, msg, data } = await orderImmediate(query);
        if (code === errorCode.success) {
          const { localNo, isFree, firstTotalPrice } = data;
          let result = null;
          // isFree 是否0元支付 0.否 1.是
          // firstTotalPrice 订单金额
          // 0元支付
          if (isFree == 1 && firstTotalPrice == 0) {
            const freePayRes = await freePay({ localNo });
            result = freePayRes.code;
          }
          // 正常支付
          else {
            const payRes = await usePayment({
              localNo,
              type: orderSourceType.daily,
            });
            result = payRes.code;
          }
          if (result === errorCode.success) {
            const ids = [
              subscribeEnum.service.workerTake,
              subscribeEnum.service.orderStart,
              subscribeEnum.service.orderAwaitConfirm,
              // subscribeEnum.service.orderComment,
            ];
            try {
              await useSubscribeTemplate(ids);
            } catch (e) {
              console.log("useSubscribeTemplate err", e);
            }
            jumpPage({
              to: "/package-service/pages/order/result",
              mode: "reLaunch",
            });
          } else {
            BasicConfig.toast("支付失败,请联系管理员!");
            setTimeout(() => {
              jumpPage({
                to: `/package-service/pages/order/order?status=${orderStatus.awaitPay}`,
                mode: "reLaunch",
              });
            }, 1000);
          }
        } else {
          BasicConfig.toast(msg);
        }
      }
    },
  });
};
onLoad((options) => {
  params.domesticServiceId = options.id;
  init();
  // getData();
});
onReady(() => {});
onUnload(() => {
  uni.$off(eventBus.service.confirm);
  uni.$off(eventBus.service.address);
});
</script>

<style lang="scss" scoped>
.page {
  background: #f7f8fa;
  width: 100vw;
  min-height: 100vh;
  font-size: 32rpx;
  .address {
    background: #ffffff;
    display: flex;
    align-items: center;
    padding: 30rpx;
    &_left {
      width: calc(100% - 16rpx);
      padding-right: 30rpx;
    }
    &_right {
      width: 16rpx;
      height: 30rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
  }
  .detail {
    background: #ffffff;
    padding: 30rpx;
    display: flex;
    align-items: center;
    margin-top: 30rpx;
    &_img {
      width: 160rpx;
      height: 160rpx;
      image {
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
      }
    }
    &_content {
      width: calc(100% - 160rpx);
      padding-left: 30rpx;
      // display: flex;
      // flex-direction: column;
      // justify-content: space-between;
      height: 100%;
      &--title {
        font-size: 36rpx;
        font-weight: 700;
      }
      &--desc {
        color: #666666;
        font-size: 34rpx;
        margin: 20rpx 0;
      }
      &--price {
        font-size: 34rpx;
        color: $main-color;
      }
    }
  }
  .time {
    padding: 30rpx;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    &_time {
      font-size: 34rpx;
      color: #333333;
    }
    &_content {
      display: flex;
      align-items: center;
      &--check {
        font-size: 34rpx;
      }
      &--icon {
        width: 16rpx;
        height: 30rpx;
        margin-left: 20rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .coupon {
    padding: 30rpx;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    &_time {
      font-size: 34rpx;
      color: #333333;
    }
    &_content {
      display: flex;
      align-items: center;
      &--check {
        font-size: 34rpx;
      }
      &--icon {
        width: 16rpx;
        height: 30rpx;
        margin-left: 20rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .foot_box {
    padding: 30rpx;
    z-index: 9;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .bill {
      font-size: 34rpx;
      display: flex;
      align-items: center;
    }
    .btn {
      width: 50%;
      padding: 30rpx;
      border-radius: 100rpx;
      text-align: center;
      font-size: 34rpx;
    }
    .btn_save {
      background: $main-color;
      color: #ffffff;
    }
  }
}
</style>
